<template>
  <div>
    <div class="sub-title">
      <div style="position: absolute; cursor: pointer; padding: 15px;" @click="cancel">
        <i class="el-icon-back" ></i>
      </div>
      <div style="padding: 13px;">{{title}}</div>
    </div>
    <div class="sub-body">
      <el-form :model="dataForm" :rules="dataRule" ref="dataForm" @keyup.enter.native="dataFormSubmit()" label-width="80px">
      <el-form-item label="项目名称" prop="name">
        <el-input :disabled="!editable" v-model="dataForm.name" placeholder=""></el-input>
      </el-form-item>
      <el-form-item label="项目分类" prop="categoryId">
        <el-select style="width: 180px" :disabled="!editable" v-model="dataForm.categoryId" clearable placeholder="请选择" size="small" filterable >
          <el-option
              v-for="item in categories"
              :key="item.id"
              :label="item.name"
              :value="item.id">
          </el-option>
        </el-select>
        <el-button-group v-if="editable">
        <el-button style="width: 41px" size="mini" type="primary" icon="el-icon-plus" @click="addCategory()"></el-button>
        <el-button style="width: 41px" size="mini" type="primary" icon="el-icon-edit" @click="editCategory()"></el-button>
        <el-button style="width: 41px" size="mini" type="primary" icon="el-icon-minus" @click="delCategory()"></el-button>
        </el-button-group>
      </el-form-item>
      <el-form-item label="简介" prop="remark">
        <el-input :disabled="!editable" v-model="dataForm.remark" placeholder=""></el-input>
      </el-form-item>
      <el-form-item label="负责人" prop="leader">
        <avatar-list :disabled="!editable" ref="leader" placeholder=""></avatar-list>
      </el-form-item>
      <el-form-item label="开始时间" prop="planStartTime">
        <el-date-picker :disabled="!editable" type="date" v-model="dataForm.planStartTime" placeholder=""></el-date-picker>
      </el-form-item>
      <el-form-item label="结束时间" prop="planEndTime">
        <el-date-picker :disabled="!editable" type="date" v-model="dataForm.planEndTime" placeholder=""></el-date-picker>
      </el-form-item>
      <el-form-item label="项目组员" prop="members">
        <avatar-list :disabled="!editable" ref="listmm" :maxNumber="20" ></avatar-list>
      </el-form-item>
      <el-form-item label="抄送人" prop="cc">
        <avatar-list :disabled="!editable" ref="listcc" :maxNumber="20" ></avatar-list>
      </el-form-item>
        <el-form-item label="项目总结" v-if="!editable">
          <div style="color:gray">{{dataForm.completeMsg}}</div>
        </el-form-item>
      </el-form>
      <div style="text-align: center">
        <el-button type="warning" @click="cancel">返回</el-button>
        <el-button v-if="editable" type="primary" @click="dataFormSubmit()" :loading="loading">确定</el-button>
        <el-button v-if="editable && this.$route.query.projectId" type="primary" @click="cancelProject()">撤销项目</el-button>
      </div>
    </div>
  </div>
</template>

<script>
  import AvatarList from '@/components/ding/avatar-list'
  import dingMixin from  '@/mixins/ding'

  export default {
    data () {
      return {
        loading: false,
        visible: false,
        title:"添加项目",
        categories:[],
        flag: 1,
        dataForm: {
          id: 0,
          name: '',
          categoryId: '',
          remark: '',
          creator: '',
          leader: '',
          createTime: '',
          planStartTime: '',
          planEndTime: '',
          endTime: '',
          members: '',
          cc: ''
        },
        dataRule: {
          name: [
            { required: true, message: '名称不能为空', trigger: 'blur' }
          ],
          categoryId:[
            { required: true, message: '项目分类不能为空', trigger: 'blur' }
          ],
          remark: [
            { required: true, message: '简介不能为空', trigger: 'blur' }
          ],
          planStartTime: [
            { required: true, message: '计划开始时间不能为空', trigger: 'blur' }
          ],
          planEndTime: [
            { required: true, message: '计划结束时间不能为空', trigger: 'blur' }
          ]
        }
      }
    },
    components:{
      AvatarList
    },
    created(){
      console.log("wpb-add created");
      this.run_dd_config();
      this.init()
      this.loadCategories()
    },
    mixins: [dingMixin],
    methods: {
      init() {
        let id = this.$route.query.projectId
        this.dataForm.id = id || 0
        this.visible = true
        this.$nextTick(() => {
          this.$refs['dataForm'].resetFields()
          if (this.dataForm.id) {
            this.title = "项目详情";
            this.$http({
              url: this.$http.adornUrl(`/wpb/projectbase/info/${this.dataForm.id}`),
              method: 'get',
              params: this.$http.adornParams()
            }).then(({data}) => {
              if (data && data.code === 0) {
                this.dataForm.name = data.projectBase.name
                this.dataForm.remark = data.projectBase.remark
                this.dataForm.creator = data.projectBase.creator
                this.dataForm.categoryId = data.projectBase.categoryId
                if(data.projectBase.leader)
                  this.$refs.leader.bindData([{emplId:data.projectBase.leader, name: data.projectBase.leaderName}])

                this.dataForm.createTime = data.projectBase.createTime
                this.dataForm.planStartTime = data.projectBase.planStartTime
                this.dataForm.planEndTime = data.projectBase.planEndTime
                this.dataForm.endTime = data.projectBase.endTime
                this.dataForm.completeMsg = data.projectBase.completeMsg
                this.flag = data.projectBase.flag

                if(data.projectBase.memberDetails && data.projectBase.memberDetails.length>0){
                  this.$refs.listmm.bindData(data.projectBase.memberDetails)
                }
                if(data.projectBase.ccDetails && data.projectBase.ccDetails.length>0) {
                  this.$refs.listcc.bindData(data.projectBase.ccDetails)
                }
              }
            })
          }
          else{
            this.title = "添加项目";
          }
        })
      },
      cancel(){
        history.go(-1);
      },
      delCategory(){
        this.$confirm(`确定要删除${this.getCategoryName(this.dataForm.categoryId)}?`, '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(()=>{
            this.$http({
              url: this.$http.adornUrl('/sys/sysdict/delete'),
              method: 'post',
              data: this.$http.adornData([this.dataForm.categoryId], false)
            }).then(({data}) => {
              if (data && data.code === 0) {
                this.categories = this.categories.filter(x=> x.id !== this.dataForm.categoryId);
                this.dataForm.categoryId = ''
              } else {
                this.$message({message: data.msg, type: 'error', duration: 1500, offset: 100})
              }
            }).catch(error=>{
              this.$message({message: data.msg, type: 'error', duration: 1500, offset: 100})
            })
          }
        );
      },
      addCategory(){
        this.$prompt('添加种类名称', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
        }).then(({ value }) => {
          this.$http({
            url: this.$http.adornUrl('/sys/sysdict/save'),
            method: 'post',
            data: this.$http.adornData({
              'name': value,
              'pid': 1,
            })
          }).then(({data}) => {
            if (data && data.code === 0) {
              this.categories.push(data.data);
                this.dataForm.categoryId = data.data.id;
            } else {
              this.$message({message: data.msg, type: 'error', duration: 1500, offset: 100})
            }
          }).catch(error=>{
            this.$message({message: error, type: 'error', duration: 1500, offset: 100})
          })
        })
      },
      editCategory(){
        this.$prompt('修改种类名称', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          inputValue: this.getCategoryName(this.dataForm.categoryId)
        }).then(({ value }) => {
          this.$http({
            url: this.$http.adornUrl('/sys/sysdict/update'),
            method: 'post',
            data: this.$http.adornData({
              'id': this.dataForm.categoryId,
              'name': value,
              'pid': 1,
            })
          }).then(({data}) => {
            if (data && data.code === 0) {
              for(let item of this.categories){
                if(item.id == this.dataForm.categoryId){
                  item.name = value;
                }
              }
            } else {
              this.$message({message: data.msg, type: 'error', duration: 1500, offset: 100})
            }
          }).catch(error=>{
            this.$message({message: error, type: 'error', duration: 1500, offset: 100})
          })
        })
      },
      getCategoryName(id){
        for(let item of this.categories){
          if(item.id == id){
            return item.name;
          }
        }
        return ''
      },
      loadCategories(){
        this.$http({
          url: this.$http.adornUrl('/wpb/projectbase/category'),
          method: 'get',
          params: this.$http.adornParams({})
        }).then(({data}) => {
          if (data && data.code === 0) {
            this.categories = data.category;
          } else {
            this.$message({message: data.msg, type: 'error', duration: 1500, offset: 100})
          }
        }).catch(error=>{
          console.log(error);
        })
      },
      cancelProject(){
          this.$confirm(`确定对该项目进行撤销操作吗?`, '提示', {
            confirmButtonText: '确定撤销',
            cancelButtonText: '不撤销',
            type: 'warning'
          }).then(()=>{
              this.$http({
                url: this.$http.adornUrl('/wpb/projectbase/cancel'),
                method: 'get',
                params: this.$http.adornParams({
                  'projectId': this.$route.query.projectId
                })
              }).then(({data}) => {
                if (data && data.code === 0) {
                  this.$message({message: '操作成功', type: 'success', duration: 1500, offset: 100})
                  this.$router.push('wpb-project');
                } else {
                  this.$message({message: data.msg, type: 'error', duration: 1500, offset: 100})
                }
              }).catch(error=>{
                this.$message({message: data.msg, type: 'error', duration: 1500, offset: 100})
              })
            }
          );
      },
      // 表单提交
      dataFormSubmit () {
        this.loading = true
        this.$refs['dataForm'].validate((valid) => {
          if (valid) {
            this.$http({
              url: this.$http.adornUrl(`/wpb/projectbase/${!this.dataForm.id ? 'save' : 'update'}`),
              method: 'post',
              data: this.$http.adornData({
                'id': this.dataForm.id || undefined,
                'categoryId': this.dataForm.categoryId,
                'name': this.dataForm.name,
                'remark': this.dataForm.remark,
                'leader': this.$refs.leader.getDingEmpIds()[0],
                'planStartTime': this.dataForm.planStartTime,
                'planEndTime': this.dataForm.planEndTime,
                'members': this.$refs.listmm.getDingEmpIds(),
                'cc': this.$refs.listcc.getDingEmpIds()
              })
            }).then(({data}) => {
              if (data && data.code === 0) {
                this.$message({message: '操作成功', type: 'success', duration: 1500, offset: 100})
                this.$router.push('wpb-project');
              } else {
                this.$message({message: data.msg, type: 'error', duration: 1500, offset: 100})
              }
            }).finally(()=>{
              this.loading = false
            })
          }else{
            this.loading = false
          }
        })
      }
    },
    computed:{
      editable(){
        return (this.flag ==1) &&  this.isManager
      }
    }
  }
</script>
<style>
  .sub-title {
    background: white;
    width:100%;
    height:50px;
    font-size: 18px;
    text-align: center;
    border-bottom: lightgray solid 1px;
    margin-bottom: 20px;
    position: relative;
  }
  .sub-body{
    padding:5px;
    max-width: 400px;
    margin: 0 auto;
  }
</style>
